/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.core.util;

public class ZByteUtil {
	private static String hexString = "0123456789ABCDEF";
	/**
	     * 整型转换为4位字节数组
	     * @param intValue
	     * @return
	     */
    public static byte[] intToByte(int intValue) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (intValue >> 8 * (3 - i) & 0xFF);
        }
        return b;
    }
    /**
     * 4位字节数组转换为整型
     * @param b
     * @return
     */
    public static int byte2Int(byte[] b) {
        int intValue = 0;
        for (int i = 0; i < b.length; i++) {
            intValue += (b[i] & 0xFF) << (8 * (3 - i));
        }
        return intValue;
    }
	/**
     * 十进制 转 二进制 并 存入byte数组里
     * @param num
     * @return
     */  
   public static byte[] intTobytes(int num){   
          byte[] b=new byte[4];   
//          int mask=0xff;   
          for(int i=0;i<4;i++){   
                b[i]=(byte)(num >>>(24-i*8));   
           }   
         return b;   
    }  
   /**
    * 二进制 转 十进制
    * @param b
    * @return
    */  
  public static int bytes2int(byte[] bytz) {   
          int mask=0xff;   
          int temp=0;   
          int res=0;   
          for(int i=0;i<4;i++){   
               res<<=8;   
               temp=bytz[i]&mask;   
               res|=temp;   
           }   
         return res;   
   }  
	public static byte charToByte(char c) {
		return (byte) hexString.indexOf(c);
	}
	public static  byte[] joinBytes(byte[] a1, byte[] a2) {
		byte[] result = new byte[a1.length + a2.length];
		System.arraycopy(a1, 0, result, 0, a1.length);
		System.arraycopy(a2, 0, result, a1.length, a2.length);
		return result;
	}
	/**
	 *  将字符串编码成16进制数字,适用于所有字符（包括中文）
	 * @param bytes
	 * @return
	 */
	public static String bytesToHex(byte[] bytes) {
		if(bytes==null){
			 throw new IllegalArgumentException("bytes must not be null");
		}
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {// 将字节数组中每个字节拆解成2位16进制整数
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}
	
	/**
	 * 将字符串编码成16进制数字,适用于所有字符（包括中文）
	 * @param bytes
	 * @return
	 */
	public static String bytesToHexWithSpace(byte[] bytes) {
		if(bytes==null){
			 throw new IllegalArgumentException("bytes must not be null");
		}
		StringBuilder sb = new StringBuilder(bytes.length * 3);
		for (int i = 0; i < bytes.length; i++) {// 将字节数组中每个字节拆解成2位16进制整数
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)+" ");
		}
		return sb.toString();
	}

	  public static String byteToHexStr(byte[] b) {
		    String stmp = "";
		    StringBuilder sb = new StringBuilder("");
		    for (int n = 0; n < b.length; n++) {
		      stmp = Integer.toHexString(b[n] & 0xFF);
		      sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
//					sb.append(" ");
		    }
		    return sb.toString().toUpperCase().trim();
		  }
	  
	public static String strToHex(String str) {
		if(str==null){
			 throw new IllegalArgumentException("str must not be null");
		}
		byte[] bytes = str.getBytes();
		return bytesToHex(bytes);
	}
	 public static byte[] hexStrToBytes(String src) {
		    int m = 0, n = 0;
		    int l = src.length() / 2;
		    byte[] ret = new byte[l];
		    for (int i = 0; i < l; i++) {
		      m = i * 2 + 1;
		      n = m + 1;
		      ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
		    }
		    return ret;
	}
	public static String hexToChinese(String hexstr){
		 StringBuffer sb=new StringBuffer(); 
           for(int i=0;i+4<=hexstr.length();i=i+4){ 
              int j=Integer.parseInt(hexstr.substring(i,i+4),16); 
               sb.append((char)j); 
           } 
          return sb.toString();
	}
	
	  public static String strToUnicode(String strText)  {
		    char c;
		    StringBuilder str = new StringBuilder();
		    int intAsc;
		    String strHex;
		    for (int i = 0; i < strText.length(); i++) {
		      c = strText.charAt(i);
		      intAsc = (int) c;
		      strHex = Integer.toHexString(intAsc);
		      if (intAsc > 128)
		        str.append("\\u" + strHex);
		      else
		        // 低位在前面补00
		        str.append("\\u00" + strHex);
		    }
		    return str.toString();
		  }
	  public static String unicodeToString(String hex) {
		    int t = hex.length() / 6;
		    StringBuilder str = new StringBuilder();
		    for (int i = 0; i < t; i++) {
		      String s = hex.substring(i * 6, (i + 1) * 6);
		      // 高位需要补上00再转
		      String s1 = s.substring(2, 4) + "00";
		      // 低位直接转
		      String s2 = s.substring(4);
		      // 将16进制的string转为int
		      int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
		      // 将int转换为字符
		      char[] chars = Character.toChars(n);
		      str.append(new String(chars));
		    }
		    return str.toString();
		  }
	/**
	 * 10进制串转为BCD码
	 * @param asc
	 * @return
	 */
	public static byte[] strToBcd(String asc) {
		if(asc==null){
			 throw new IllegalArgumentException("asc must not be null");
		}
		int len = asc.length();
		int mod = len % 2;

		if (mod != 0) {
			asc = "0" + asc;
			len = asc.length();
		}

		byte abt[] = new byte[len];
		if (len >= 2) {
			len = len / 2;
		}

		byte bbt[] = new byte[len];
		abt = asc.getBytes();
		int j, k;

		for (int p = 0; p < asc.length() / 2; p++) {
			if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
				j = abt[2 * p] - '0';
			} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
				j = abt[2 * p] - 'a' + 0x0a;
			} else {
				j = abt[2 * p] - 'A' + 0x0a;
			}

			if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
				k = abt[2 * p + 1] - '0';
			} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
				k = abt[2 * p + 1] - 'a' + 0x0a;
			} else {
				k = abt[2 * p + 1] - 'A' + 0x0a;
			}

			int a = (j << 4) + k;
			byte b = (byte) a;
			bbt[p] = b;
		}
		return bbt;
	}
	public static byte[] asciiToBcd(byte[] ascii, int asc_len) {
		byte[] bcd = new byte[asc_len / 2];
		int j = 0;
		for (int i = 0; i < (asc_len + 1) / 2; i++) {
			bcd[i] = ascToBcd(ascii[j++]);
			bcd[i] = (byte) (((j >= asc_len) ? 0x00 : ascToBcd(ascii[j++])) + (bcd[i] << 4));
		}
		return bcd;
	}
	
	public static byte ascToBcd(byte asc) {
		byte bcd;

		if ((asc >= '0') && (asc <= '9'))
			bcd = (byte) (asc - '0');
		else if ((asc >= 'A') && (asc <= 'F'))
			bcd = (byte) (asc - 'A' + 10);
		else if ((asc >= 'a') && (asc <= 'f'))
			bcd = (byte) (asc - 'a' + 10);
		else
			bcd = (byte) (asc - 48);
		return bcd;
	}
	/**
	 *  BCD码转为10进制串(阿拉伯数据) 
	 * @param bytes
	 * @return
	 */
    public static String bcdToStr(byte[] bytes) {  
    	if(bytes==null){
			 throw new IllegalArgumentException("bytes must not be null");
		}
    	 String temp =bytesToHex(bytes);
        return temp.substring(0, 1).equalsIgnoreCase("0") ? temp  
                .toString().substring(1) : temp.toString();  
    }  
    
}
